document.getElementById('searchBtn').addEventListener('click', function() {
    document.getElementById('loading').style.display = 'table-row';
    getTickets();
}, false)

function getTickets() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200 || xhr.status == 304) {
                var ticketsInfo = JSON.parse(xhr.responseText);
                console.log(ticketsInfo);
                ticketsRender(ticketsInfo);
                document.getElementById('loading').style.display = 'none';
            } else {
                console.log(xhr.status);
            }
        }
    }
    xhr.open("get", "http://www.yunwii.com:9999/ticketSlow", true);
    xhr.send(null);
}

function ticketsRender(object) {
    var str = '';
    var ticketData = '';
    var dateStr = getTime();
    for (i = 0; i < object.length; i++) {
        ticketData = "<tr>" +
            "<td>" + object[i]["trainID"] + "</td>" +
            "<td><i class='start'>始</i>" + object[i]["fromCity"] + "<br><i class='end'>终</i>" + object[i]["toCity"] + "</td>" +
            "<td>" + dateStr + "<br>" + dateStr + "</td>" +
            "<td>" + object[i]["wholeTime"] + "</td>" +
            "<td>" + object[i]["business"] + "</td>" +
            "<td>" + object[i]["special"] + "</td>" +
            "<td>" + object[i]["first"] + "</td>" +
            "<td>" + object[i]["second"] + "</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td>--</td>" +
            "<td><span class='reserve-btn'>预定</span></td>" +
            "</tr>";
        str += ticketData;
    }

    if (document.getElementById('ticketsData')) {
        return false;
    } else {
        var el = document.createElement('tbody');
        document.getElementById('ticketsTable').appendChild(el);
        el.innerHTML = str;
        el.setAttribute('id', 'ticketsData');
    }
}

function getTime(el) {
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    if (hours < 10) {
        hours = '0' + hours;
    }
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    var dateStr = hours + ':' + minutes;
    return dateStr;
}
